package com.ainiyar.springweb.service.impl;

import com.ainiyar.springweb.common.result.ResultResponse;
import com.ainiyar.springweb.mapper.MenuMapper;
import com.ainiyar.springweb.pojo.admin.vo.RolePermissionVo;
import com.ainiyar.springweb.pojo.admin.vo.SelectVo;
import com.ainiyar.springweb.pojo.entity.Menu;
import com.ainiyar.springweb.service.MenuService;
import com.ainiyar.springweb.util.MenuTreeUtils;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.update.UpdateChain;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

import static com.ainiyar.springweb.pojo.entity.table.MenuTableDef.MENU;

/**************************************
 * File Name : MenuServiceImpl
 * Created with : IntelliJ IDEA.
 * Author : 艾尼亚尔·毛拉吾提
 * QQ : 524155792  WeChat : ainiyar0124
 * Created Time : 2024/2/5  00:51
 * Desc :菜单权限Service
 ***************************************/
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {
    @Resource
    private MenuMapper menuMapper;

    /**
     * 为超级管理员获取菜单权限
     *
     * @return List<Menu>
     */
    @Override
    public List<Menu> findPermissionListForSuperSuperAdmin() {
        QueryWrapper queryWrapper = QueryWrapper.create()
                .select(MENU.ID, MENU.NAME, MENU.PARENT_ID, MENU.PARENT_NAME, MENU.LABEL, MENU.CODE, MENU.URL, MENU.TYPE, MENU.ICON, MENU.E_LINK, MENU.HIDE_MENU
                )
                .where(MENU.IS_DELETE.eq(0))
                .orderBy(MENU.SORT.asc());

        return menuMapper.selectListByQuery(queryWrapper);
    }

    /**
     * 根据登录人id获取菜单权限
     *
     * @param admin_id 当前登录人id
     * @return List<Menu>
     */
    @Override
    public List<Menu> findPermissionListByAdminId(Long admin_id) {
        List<Object> menuIds= menuMapper.findPermissionListByAdminId(admin_id);
        QueryWrapper queryWrapper = QueryWrapper.create()
                .select(MENU.ID, MENU.NAME, MENU.PARENT_ID, MENU.PARENT_NAME, MENU.LABEL, MENU.CODE, MENU.URL, MENU.TYPE, MENU.ICON, MENU.E_LINK, MENU.HIDE_MENU)
                .where(MENU.IS_DELETE.eq(0))
                .where(MENU.ID.in(menuIds))
                .orderBy(MENU.SORT.asc());
        return menuMapper.selectListByQuery(queryWrapper);
    }

    /**
     * 菜单权限列表
     *
     * @return 菜单列表
     */
    @Override
    public ResultResponse<List<Menu>> lists() {
        QueryWrapper queryWrapper = QueryWrapper.create()
                .select(MENU.DEFAULT_COLUMNS)
                .where(MENU.IS_DELETE.eq(0))
                .orderBy(MENU.SORT.asc());
        List<Menu> list = menuMapper.selectListByQuery(queryWrapper);
        if (list.isEmpty()) {
            return ResultResponse.Result(list);
        }
        return ResultResponse.Result(MenuTreeUtils.makeMenuTree(list, 0L));
    }

    /**
     * 保存数据
     *
     * @param menu 菜单权限数据
     * @return true:成功  false:失败
     */
    @Override
    public boolean saveAddEditMenu(Menu menu) {
        Menu menuEntity = new Menu();
        //修改时添加id
        if (menu.getId() != null && menu.getId() != 0) {
            menuEntity.setId(menu.getId());
        }
        menuEntity.setLabel(menu.getLabel());
        menuEntity.setParentId(menu.getParentId());
        menuEntity.setParentName(menu.getParentId() != 0 ? getPermissionLabelById(menu.getParentId()) : "顶级菜单");
        menuEntity.setCode(menu.getCode());
        menuEntity.setName(menu.getName());
        menuEntity.setELink(menu.getELink());
        menuEntity.setHideMenu(menu.getHideMenu());
        menuEntity.setIcon(menu.getIcon());
        menuEntity.setUrl(menu.getUrl());
        menuEntity.setSort(menu.getSort());
        menuEntity.setType(menu.getType());
        return menuMapper.insertOrUpdateSelective(menuEntity) > 0;
    }

    /**
     * 删除菜单数据
     *
     * @param id id
     * @return boolean
     */
    @Override
    public boolean deleteMenu(Long id) {
        //软删除
        return UpdateChain.of(Menu.class)
                .set(MENU.IS_DELETE, 1)
                .where(MENU.ID.eq(id)).update();
    }

    @Override
    public boolean hasChildren(Long id) {
        return false;
    }

    @Override
    public boolean isBindRole(Long per_id) {
        return false;
    }

    /**
     * 为下拉框
     */
    @Override
    public List<SelectVo> getForSelect() {
        QueryWrapper queryWrapper = QueryWrapper.create()
                .select(MENU.DEFAULT_COLUMNS)
                //未删除的
                .where(MENU.IS_DELETE.eq(0))
                //类型不是按钮的
                .and(MENU.TYPE.ne(3))
                .orderBy(MENU.SORT.asc());
        List<Menu> menuList = menuMapper.selectListByQuery(queryWrapper);
        return buildTreeVo(menuList, 0L);
    }
    /**
     * 为角色列表
     * @param ids 菜单权限 id
     * @return PermissionEntity
     */
    @Override
    public List<Menu> getMenuForRoleByIds(Object ids) {
        QueryWrapper queryWrapper=QueryWrapper.create()
                .select(MENU.ID,MENU.LABEL,MENU.PARENT_ID,MENU.TYPE,MENU.CREATE_TIME)
                .where(MENU.ID.in(ids));
        return MenuTreeUtils.makeMenuTree(menuMapper.selectListByQuery(queryWrapper),0L);
    }

    /**
     * 为角色配置权限
     */
    @Override
    public List<RolePermissionVo> getMenuForPermission() {
        QueryWrapper queryWrapper = QueryWrapper.create()
                .select(MENU.DEFAULT_COLUMNS)
                .where(MENU.IS_DELETE.ne(1))
                .orderBy(MENU.SORT.asc());
        List<Menu> list = menuMapper.selectListByQuery(queryWrapper);
        return buildRolePermissionTree(list, 0L);
    }

    private List<RolePermissionVo> buildRolePermissionTree(List<Menu> menu, Long pid) {
        List<RolePermissionVo> tree_list = new ArrayList<RolePermissionVo>();
        Optional.ofNullable(menu).orElse(new ArrayList<Menu>())
                .stream().filter(item -> item != null && Objects.equals(item.getParentId(), pid))
                .forEach(item -> {
                    RolePermissionVo treeVo = new RolePermissionVo();
                    treeVo.setLabel(item.getLabel());
                    treeVo.setKey(item.getId());
                    treeVo.setType(item.getType());
                    //递归生成我们的路由
                    List<RolePermissionVo> children = buildRolePermissionTree(menu, item.getId());
                    treeVo.setChildren(!children.isEmpty() ? children : null);
                    tree_list.add(treeVo);
                });
        return tree_list;
    }

    /**
     * 树形结构
     *
     * @param menu 菜单权限
     * @param pid  上级id
     * @return List<SelectValue>
     */
    private List<SelectVo> buildTreeVo(List<Menu> menu, Long pid) {
        List<SelectVo> tree_list = new ArrayList<SelectVo>();
        Optional.ofNullable(menu).orElse(new ArrayList<Menu>())
                .stream().filter(item -> item != null && Objects.equals(item.getParentId(), pid))
                .forEach(item -> {
                    SelectVo treeVo = new SelectVo();
                    treeVo.setLabel(item.getLabel());
                    treeVo.setKey(item.getId());
                    //递归生成我们的路由
                    List<SelectVo> children = buildTreeVo(menu, item.getId());
                    treeVo.setChildren(!children.isEmpty() ? children : null);
                    tree_list.add(treeVo);
                });
        return tree_list;
    }

    public String getPermissionLabelById(Long id) {
        QueryWrapper queryWrapper = QueryWrapper.create()
                .select(MENU.DEFAULT_COLUMNS)
                .where(MENU.ID.eq(id));
        Menu permission = menuMapper.selectOneByQuery(queryWrapper);
        return permission.getLabel();
    }
}

